// Package database @program: chat
//@author: edte
//@create: 2021-12-28 22:39
package database

import (
	log2 "chat/log"
	"chat/tools"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-redis/redis/v8"
	"strconv"
	"time"
)

func SendMessage(ctx context.Context, roomId int, userId int, message string, nickname string) (string, error) {
	redisPath := tools.GetEnv("REDIS_PATH", "localhost:6379")
	redisPD := tools.GetEnv("REDIS_PASSWORD", "")
	rdb := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       2,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	result, err := rdb.SIsMember(ctx, strconv.Itoa(roomId), userId).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "SendMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return "", err
	}
	if result == false {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "SendMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Debug", "If you have not joined the chat room, you have no permission to send message records")
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return "", errors.New("未加入聊天室,无权限发送消息记录")
	}
	rdb2 := redis.NewClient(&redis.Options{
		Addr:     redisPath,
		Password: redisPD, // no password set
		DB:       4,       // use default DB
		//PoolSize: 500, // 连接池大小
	})
	messages := tools.Message{Message: message, UserId: userId, DateTime: time.Now().Format("2006-01-02 15:04:05"), NickName: nickname}
	messageJson, err := json.Marshal(&messages)
	_, err = rdb2.RPush(ctx, strconv.Itoa(roomId), messageJson).Result()
	if err != nil {
		writeLog, err2 := log2.WriteLog(ctx, "chat", "SendMessage", "userid:"+strconv.Itoa(userId)+" roomid:"+strconv.Itoa(roomId), "Warring", err.Error())
		if writeLog == 200 {
			fmt.Println("成功写入日志")
		}
		if err2 != nil {
			fmt.Println("写入日志失败")
		}
		return "", err
	}

	return string(messageJson), err
}
